#include "head.h"
int main(int argc, char *argv[])
{
    // ./server 192.168.38.128 1234 3
    ARGS_CHECK(argc,4);
    workerData_t workerDataArr[10];
    int workerNum = atoi(argv[3]);
    makeWorker(workerNum,workerDataArr);
    int sockfd;
    tcpInit(argv[1],argv[2],&sockfd); 

    int epfd = epoll_create(1);
    epollAdd(epfd,sockfd);
    for(int i = 0; i < workerNum; ++i){
        epollAdd(epfd,workerDataArr[i].socketpair);
    }

    struct epoll_event readyset[1024];
    while(1){
        int readyNum = epoll_wait(epfd,readyset,1024,-1);
        for(int i = 0; i < readyNum; ++i){
            if(readyset[i].data.fd == sockfd){
                int netfd = accept(sockfd,NULL,NULL);
                // 主进程取出了一条连接
                for(int j = 0; j < workerNum; ++j){
                    if(workerDataArr[j].status == FREE){
                        // 找到空闲的子进程，将netfd发送它
                       printf("%d worker is free, pid = %d\n",
                              j, workerDataArr[j].pid);
                       sendfd(workerDataArr[j].socketpair, netfd); 
                       workerDataArr[j].status = BUSY;
                       break;
                    }
                }
                close(netfd);
            }
            else{
                for(int j = 0; j < workerNum; ++j){
                    if(readyset[i].data.fd == workerDataArr[j].socketpair){
                        pid_t pid;
                        read(readyset[i].data.fd, &pid, sizeof(pid));
                        workerDataArr[j].status = FREE;
                        printf("%d worker is ready! pid = %d\n", j, pid);
                    }
                }
            }
        }
    }
    return 0;
}

